// 内容管理器
class ContentManager {
    constructor() {
        this.currentContent = null;
        this.contentFrame = document.getElementById('contentFrame');
        this.currentContentDisplay = document.getElementById('currentContent');
        this.loadingOverlay = document.getElementById('loadingOverlay');
        this.durationTimer = null;
        
        // 监听iframe消息
        this.setupMessageListener();
    }

    // 设置消息监听器
    setupMessageListener() {
        window.addEventListener('message', (event) => {
            // 验证消息来源 - 只处理来自当前iframe的消息
            if (event.source !== this.contentFrame.contentWindow) {
                return;
            }

            console.log('收到iframe消息:', event.data);
            this.handleIframeMessage(event.data);
        });
    }

    // 处理iframe消息
    handleIframeMessage(data) {
        switch (data.type) {
            case 'contentLoaded':
                this.hideLoading();
                break;
            case 'contentLoading':
                this.showLoading();
                break;
            case 'contentError':
                this.hideLoading();
                this.showError(data.message || '内容加载失败');
                break;
            case 'contentReady':
                // 内容准备就绪
                break;
        }
    }

    // 显示内容
    async displayContent(data) {
        try {
            this.showLoading();
            this.currentContent = data;
            this.updateContentDisplay(data);

            switch (data.type) {
                case CONFIG.messageTypes.WEBPAGE:
                    await this.displayWebpage(data);
                    break;
                case CONFIG.messageTypes.IMAGE:
                    await this.displayImage(data);
                    break;
                case CONFIG.messageTypes.VIDEO:
                    await this.displayVideo(data);
                    break;
                case CONFIG.messageTypes.TEXT:
                    await this.displayText(data);
                    break;
                case CONFIG.messageTypes.CLEAR:
                    this.clearContent();
                    break;
                default:
                    throw new Error(CONFIG.errors.unsupportedType);
            }

            // 设置显示时长
            this.setDuration(data.duration);

        } catch (error) {
            console.error('显示内容失败:', error);
            this.showError(error.message);
            this.hideLoading();
        }
    }

    // 显示网页
    async displayWebpage(data) {
        // 设置超时处理
        const timeout = setTimeout(() => {
            this.hideLoading();
        }, 10000); // 10秒超时
        
        // 设置iframe加载事件监听
        this.contentFrame.onload = () => {
            clearTimeout(timeout);
            this.hideLoading();
        };
        
        this.contentFrame.onerror = () => {
            clearTimeout(timeout);
            this.hideLoading();
            this.showError('网页加载失败');
        };
        
        this.contentFrame.src = data.url;
    }

    // 显示图片
    async displayImage(data) {
        const imagePage = this.createImagePage(data);
        this.loadContentPage(imagePage);
    }

    // 显示视频
    async displayVideo(data) {
        // 使用本地的video-player.html页面
        this.contentFrame.src = 'video-player.html';
        
        // 等待iframe加载完成后发送视频URL
        this.contentFrame.onload = () => {
            // 延迟一点时间确保video-player页面完全初始化
            setTimeout(() => {
                this.contentFrame.contentWindow.postMessage({
                    type: 'loadVideo',
                    url: data.url
                }, '*');
                
                // 如果设置了自动播放，发送播放命令
                if (data.autoplay !== false) {
                    setTimeout(() => {
                        this.contentFrame.contentWindow.postMessage({
                            type: 'play'
                        }, '*');
                    }, 1500); // 增加延迟时间，确保视频加载完成
                }
                
                this.hideLoading();
            }, 500);
        };
        
        this.contentFrame.onerror = () => {
            this.hideLoading();
            this.showError('视频播放器加载失败');
        };
    }

    // 显示文本
    async displayText(data) {
        const textPage = this.createTextPage(data);
        this.loadContentPage(textPage);
    }

    // 创建图片页面HTML
    createImagePage(data) {
        return `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>${data.title || '图片显示'}</title>
                <style>
                    * {
                        margin: 0;
                        padding: 0;
                        box-sizing: border-box;
                    }
                    body {
                        width: 100vw;
                        height: 100vh;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        background: #000;
                        overflow: hidden;
                    }
                    img {
                        max-width: 100%;
                        max-height: 100%;
                        object-fit: contain;
                    }
                </style>
            </head>
            <body>
                <img src="${data.url}" alt="${data.title || '图片'}" 
                     onload="parent.postMessage({type: 'contentLoaded'}, '*')"
                     onerror="parent.postMessage({type: 'contentError', message: '图片加载失败'}, '*')">
            </body>
            </html>
        `;
    }

    // 创建视频页面HTML
    createVideoPage(data) {
        const autoplay = data.autoplay !== false ? 'autoplay' : '';
        const loop = data.loop ? 'loop' : '';
        const muted = data.muted !== false ? 'muted' : '';
        const controls = data.controls ? 'controls' : '';

        return `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>${data.title || '视频播放'}</title>
                <style>
                    * {
                        margin: 0;
                        padding: 0;
                        box-sizing: border-box;
                    }
                    body {
                        width: 100vw;
                        height: 100vh;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        background: #000;
                        overflow: hidden;
                    }
                    video {
                        max-width: 100%;
                        max-height: 100%;
                        object-fit: contain;
                    }
                </style>
            </head>
            <body>
                <video ${autoplay} ${loop} ${muted} ${controls}
                       onloadeddata="parent.postMessage({type: 'contentLoaded'}, '*')"
                       onerror="parent.postMessage({type: 'contentError', message: '视频加载失败'}, '*')">
                    <source src="${data.url}" type="video/mp4">
                    您的浏览器不支持视频播放。
                </video>
            </body>
            </html>
        `;
    }

    // 创建文本页面HTML
    createTextPage(data) {
        return `
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>${data.title || '文本显示'}</title>
                <style>
                    * {
                        margin: 0;
                        padding: 0;
                        box-sizing: border-box;
                    }
                    body {
                        width: 100vw;
                        height: 100vh;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        background: #000;
                        color: #fff;
                        font-family: 'Microsoft YaHei', Arial, sans-serif;
                        font-size: 48px;
                        text-align: center;
                        padding: 20px;
                        overflow: hidden;
                    }
                    .text-content {
                        max-width: 90%;
                        word-wrap: break-word;
                    }
                </style>
            </head>
            <body>
                <div class="text-content">${data.content}</div>
                <script>
                    parent.postMessage({type: 'contentLoaded'}, '*');
                </script>
            </body>
            </html>
        `;
    }

    // 加载内容页面到iframe
    loadContentPage(htmlContent) {
        const blob = new Blob([htmlContent], { type: 'text/html' });
        const url = URL.createObjectURL(blob);
        
        // 设置加载事件监听
        this.contentFrame.onload = () => {
            URL.revokeObjectURL(url);
            // 自定义HTML内容会通过postMessage通知加载完成，这里只清理资源
        };
        
        this.contentFrame.onerror = () => {
            URL.revokeObjectURL(url);
            this.hideLoading();
            this.showError('内容加载失败');
        };
        
        this.contentFrame.src = url;
    }

    // 清除内容
    clearContent() {
        this.contentFrame.src = 'about:blank';
        this.currentContent = null;
        this.updateContentDisplay(null);
        this.hideLoading();
        this.clearDuration();
    }

    // 显示加载动画
    showLoading() {
        this.loadingOverlay.classList.remove('hidden');
    }

    // 隐藏加载动画
    hideLoading() {
        this.loadingOverlay.classList.add('hidden');
    }

    // 更新内容显示信息
    updateContentDisplay(data) {
        if (data) {
            const typeText = {
                [CONFIG.messageTypes.WEBPAGE]: '网页',
                [CONFIG.messageTypes.IMAGE]: '图片',
                [CONFIG.messageTypes.VIDEO]: '视频',
                [CONFIG.messageTypes.TEXT]: '文本',
                [CONFIG.messageTypes.CLEAR]: '清除'
            }[data.type] || '未知';
            
            this.currentContentDisplay.textContent = `${typeText}: ${data.title || data.url || data.content || '无标题'}`;
        } else {
            this.currentContentDisplay.textContent = '等待指令...';
        }
    }

    // 设置显示时长
    setDuration(duration) {
        this.clearDuration();
        
        if (duration && duration > 0) {
            this.durationTimer = setTimeout(() => {
                this.clearContent();
            }, duration);
        }
    }

    // 清除时长定时器
    clearDuration() {
        if (this.durationTimer) {
            clearTimeout(this.durationTimer);
            this.durationTimer = null;
        }
    }

    // 显示错误信息
    showError(message) {
        const errorDisplay = document.getElementById('errorDisplay');
        const errorMessage = document.getElementById('errorMessage');
        
        errorMessage.textContent = message;
        errorDisplay.classList.remove('hidden');
        
        // 3秒后自动隐藏错误信息
        setTimeout(() => {
            errorDisplay.classList.add('hidden');
        }, 3000);
    }
} 